package com.example.backend.controller;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.backend.common.EncryptUtil;
import com.example.backend.entity.Card;
import com.example.backend.entity.User;
import com.example.backend.entity.UserCard;
import com.example.backend.mapper.CardMapper;
import com.example.backend.mapper.DesignProductMapper;
import com.example.backend.mapper.UserCardMapper;
import com.example.backend.mapper.UserMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import jakarta.websocket.server.PathParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;
import static org.springframework.web.bind.annotation.RequestMethod.*;

@RestController
public class UserCardController {
    @Resource
    UserCardMapper userCardMapper;
    @Resource
    UserMapper userMapper;
    @Resource
    CardMapper cardMapper;
    @RequestMapping(value ="/userCard",method = GET)
    String getUserCard(@RequestParam(value = "openId", required = true) String openId){
        //获取用户数字藏品列表
        List<UserCard> users = userCardMapper.getUserCardById(openId);
        //对数字藏品进行分组排序
        Map<String,List<UserCard>> stringListMap =
                users.stream().sorted(Comparator.comparing(UserCard::getDate).
                        reversed()).collect(Collectors.
                        groupingBy(UserCard::getCategory));
        String result=null;
        //定义对象转换器
        ObjectMapper mapper = new ObjectMapper();
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
        try {
            //加密
            result= EncryptUtil.encrypt(Convert.toStr(mapper.writeValueAsString(stringListMap)));
        }catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @PutMapping(value ="/userCardCollect")
    UserCard updateUserCardCollected(@RequestBody UserCard user){
        UserCard userCard  = userCardMapper.getSingleUserCardById(user.getId());
        System.out.println(userCard);
        if(userCard != null){
            if(userCard.getCollect()==1){
                userCardMapper.updateUsersCard(0,user.getId());
            }
            else{
                userCardMapper.updateUsersCard(1,user.getId());
            }
        }
        return null;
    }

    @RequestMapping(value ="/getCard",method = GET)
    String getOneCard(@RequestParam(value = "openId", required = true) String openId){
        List<UserCard> users = userCardMapper.getUserCardById(openId);
        List<Integer> idCollected = new ArrayList<Integer>();
        if(!users.isEmpty()){
            users.forEach(item->{
                idCollected.add(item.getCardId());
            });
        }
        ObjectMapper mapper = new ObjectMapper();
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
        List<Integer> idAll = new ArrayList<Integer>();
        List<Card> cards=cardMapper.selectList(null);
        if(!cards.isEmpty())
            cards.forEach(card -> {
                idAll.add(card.getId());
            });
        List<Integer> idReduce = idAll.stream().filter(item -> !idCollected.contains(item)).collect(toList());
        Random random = new Random();
        int RandomNum=random.nextInt(idReduce.size());
        Card card=cardMapper.selectById(idReduce.get(RandomNum));
        System.out.println(card);
        UserCard userCardLink = new UserCard();
        userCardLink.setCardId(idReduce.get(RandomNum));
        userCardLink.setDate(new Date());
        userCardLink.setCollect(0);
        userCardLink.setUserId(openId);
        userCardMapper.insert(userCardLink);
        ObjectMapper objectMapper = new ObjectMapper();
        userCardMapper.updateUserTime(openId);
        String result=null;
        try {
            result= EncryptUtil.encrypt(Convert.toStr(mapper.writeValueAsString(card)));
        }catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
